const Address = require('../models/address');

// 获取用户所有地址
exports.getUserAddresses = async (req, res) => {
  try {
    const user_id = req.user.id;
    console.log('🔍 获取用户地址，用户ID:', user_id);
    
    const addresses = await Address.findByUserId(user_id);
    
    console.log('✅ 从数据库获取到地址数量:', addresses.length);
    
    res.json({
      success: true,
      data: addresses,
      message: '获取地址列表成功'
    });
  } catch (error) {
    console.error('❌ 获取地址列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取地址列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

exports.getDefaultAddress = async (req, res) => {
  try {
    const user_id = req.user.id;
    console.log('🔍 获取用户默认地址，用户ID:', user_id);
    
    const defaultAddress = await Address.findDefaultByUserId(user_id);
    
    console.log('✅ 默认地址:', defaultAddress ? '存在' : '不存在');
    
    res.json({
      success: true,
      data: defaultAddress,
      message: defaultAddress ? '获取默认地址成功' : '暂无默认地址'
    });
  } catch (error) {
    console.error('❌ 获取默认地址错误:', error);
    res.status(500).json({
      success: false,
      message: '获取默认地址失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

exports.createAddress = async (req, res) => {
  try {
    const user_id = req.user.id;
    const { recipient, phone, province, city, district, detail, is_default } = req.body;
    
    console.log('🔍 创建地址请求，用户ID:', user_id, '数据:', req.body);

    // 验证必填字段
    if (!recipient || !phone || !province || !city || !district || !detail) {
      return res.status(400).json({
        success: false,
        message: '请填写完整的地址信息'
      });
    }
    
    // 调用模型方法创建地址
    const addressId = await Address.create({
      user_id,
      recipient,
      phone,
      province,
      city,
      district,
      detail,
      is_default: is_default || false
    });

    console.log('✅ 地址创建成功，数据库ID:', addressId);
    
    res.status(201).json({
      success: true,
      data: { id: addressId },
      message: '地址创建成功'
    });
  } catch (error) {
    console.error('❌ 创建地址错误:', error);
    res.status(500).json({
      success: false,
      message: '创建地址失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

exports.updateAddress = async (req, res) => {
  try {
    const user_id = req.user.id;
    const addressId = req.params.id;
    const { recipient, phone, province, city, district, detail, is_default } = req.body;
    
    console.log('🔍 更新地址，地址ID:', addressId, '用户ID:', user_id, '数据:', req.body);

    // 检查地址是否存在且属于当前用户
    const existingAddress = await Address.findById(addressId);
    if (!existingAddress) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    if (existingAddress.user_id !== user_id) {
      return res.status(403).json({
        success: false,
        message: '无权操作此地址'
      });
    }

    const updated = await Address.update(addressId, {
      user_id,
      recipient,
      phone,
      province,
      city,
      district,
      detail,
      is_default: is_default || false
    });

    if (updated) {
      console.log('✅ 地址更新成功');
      res.json({
        success: true,
        message: '地址更新成功'
      });
    } else {
      console.log('❌ 地址更新失败');
      res.status(400).json({
        success: false,
        message: '地址更新失败'
      });
    }
  } catch (error) {
    console.error('❌ 更新地址错误:', error);
    res.status(500).json({
      success: false,
      message: '更新地址失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

exports.deleteAddress = async (req, res) => {
  try {
    const user_id = req.user.id;
    const addressId = req.params.id;
    
    console.log('🔍 删除地址，地址ID:', addressId, '用户ID:', user_id);

    // 检查地址是否存在且属于当前用户
    const existingAddress = await Address.findById(addressId);
    if (!existingAddress) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    if (existingAddress.user_id !== user_id) {
      return res.status(403).json({
        success: false,
        message: '无权删除此地址'
      });
    }

    const deleted = await Address.delete(addressId, user_id);

    if (deleted) {
      console.log('✅ 地址删除成功');
      res.json({
        success: true,
        message: '地址删除成功'
      });
    } else {
      console.log('❌ 地址删除失败');
      res.status(400).json({
        success: false,
        message: '地址删除失败'
      });
    }
  } catch (error) {
    console.error('❌ 删除地址错误:', error);
    res.status(500).json({
      success: false,
      message: '删除地址失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

exports.setDefaultAddress = async (req, res) => {
  try {
    const user_id = req.user.id;
    const addressId = req.params.id;
    
    console.log('🔍 设置默认地址，地址ID:', addressId, '用户ID:', user_id);

    // 检查地址是否存在且属于当前用户
    const existingAddress = await Address.findById(addressId);
    if (!existingAddress) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    if (existingAddress.user_id !== user_id) {
      return res.status(403).json({
        success: false,
        message: '无权操作此地址'
      });
    }

    const updated = await Address.setDefault(addressId, user_id);

    if (updated) {
      console.log('✅ 设置默认地址成功');
      res.json({
        success: true,
        message: '设置默认地址成功'
      });
    } else {
      console.log('❌ 设置默认地址失败');
      res.status(400).json({
        success: false,
        message: '设置默认地址失败'
      });
    }
  } catch (error) {
    console.error('❌ 设置默认地址错误:', error);
    res.status(500).json({
      success: false,
      message: '设置默认地址失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

console.log('✅ 地址控制器初始化完成（使用真实数据库操作）');